package com.veetao.api.req;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.veetao.api.annotation.DocIgnore;
import com.veetao.api.annotation.Required;
import com.veetao.api.utils.NumberUtil;

public class ExtraParams {

	@Required(value=false, desc="服务端返回的extra字段原封不动带回,用于计算分页数据")
	private String extras;

	
	
	public ExtraParams() {
		super();
	}
	
	@DocIgnore
	@JsonIgnore
	private Map<String,String> extraMap;
	public void putExtra(String key, long value) {
		this.putExtra(key, value+"");
	}
	public void putExtra(String key, String value) {
		if(this.extraMap == null) {
			this.extraMap = new HashMap<String, String>();
		}
		
		this.extraMap.put(key, value);
	}
	
	private Map<String,String> generateParams(String s) {
		if(s == null) {
			return Collections.emptyMap();
		}
		try {
			s = URLDecoder.decode(s, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Collections.emptyMap();
		}
		String params[] = s.split("&");
		Map<String, String> result = new HashMap<String, String>();
		for(String param : params) {
			String[] a = param.split("=");
			if(a.length < 2) {
				continue;
			}
			result.put(a[0], a[1]);
		}
		
		return result;
	}
	
	private String serializeExtra() {
		if(this.extraMap == null || this.extraMap.size() == 0) {
			return "";
		}
		
		StringBuilder sb = new StringBuilder();
		for(String key : extraMap.keySet()) {
			sb.append(key).append("=").append(extraMap.get(key));
			sb.append("&");
		}
		
		if(sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		try {
			return URLEncoder.encode(sb.toString(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
		
	}
	
	public String getExtraData(String key) {
		if(this.extraMap == null) {
			extraMap = generateParams(this.extras);
		}
		
		return this.extraMap.get(key);
	}
	
	public int getExtraInt(String key) {
		if(this.extraMap == null) {
			extraMap = generateParams(this.extras);
		}
		
		String v = this.extraMap.get(key);
		if(v != null && NumberUtil.isNumber(v)) {
			return Integer.parseInt(v);
		}
		
		return 0;
	}
	
	public long getExtraLong(String key) {
		if(this.extraMap == null) {
			extraMap = generateParams(this.extras);
		}
		
		String v = this.extraMap.get(key);
		if(v != null && NumberUtil.isNumber(v)) {
			return Long.parseLong(v);
		}
		
		return 0;
	}
	


	public String getExtras() {
		if(extras == null) {
			extras = serializeExtra();
		}
		return extras;
	}

	public void setExtras(String extras) {
		this.extras = extras;
	}
	
	@JsonIgnore
	public Map<String, String> getExtraMap() {
		return extraMap;
	}
	

}
